import {
  app,
  LoadFileOptions, LoadURLOptions,
} from 'electron';
import { command } from '../../command';
import { Environment } from '../../environment/environment';
import { store } from '../../store';
import { BaseWindow } from '../base-window/base-window';

/**
 * 单一应用窗口
 *
 * @author chitanda
 * @date 2022-06-07 19:06:13
 * @export
 * @class AppWindow
 */
export class AppWindow extends BaseWindow {
  /**
   * 打开文件型
   *
   * @author chitanda
   * @date 2022-06-07 19:06:34
   * @param {string} filePath
   * @param {LoadFileOptions} [options]
   * @return {*}  {Promise<void>}
   */
  async openFile(filePath: string, options?: LoadFileOptions): Promise<void> {
    this.init();
    await this.loadFile(filePath, options);
  }

  /**
   * 打开 url 形式
   *
   * @author chitanda
   * @date 2022-06-07 19:06:27
   * @param {string} url
   * @param {LoadURLOptions} [options]
   * @return {*}  {Promise<void>}
   */
  async openUrl(url: string, options?: LoadURLOptions): Promise<void> {
    this.init();
    await this.loadURL(url, options);
  }

  protected init(): void {
    super.init();

    if (!app.isPackaged) {
      this.webContents.openDevTools();
    }

    const { webRequest } = this.webContents.session;

    const filter = { urls: [`${Environment.AppCenterBackendUrl}/*`, `${Environment.MosDynamicBackendUrl}/*`] }

    webRequest.onErrorOccurred(filter, async details => {
      const data = details as unknown as Record<string, string | number>;
      if (data.statusCode === 401) {
        await command.login();
      }
    });

    webRequest.onCompleted(filter, (details) => {
      const data = details as unknown as Record<string, string | number>;
      if (data.statusCode === 401) {
        command.login();
      }
    });

    webRequest.onBeforeSendHeaders(filter, (details, callback) => {
      const token = store.get('token');
      if (token) {
        details.requestHeaders['Authorization'] = `Bearer ${token}`;
        callback({ requestHeaders: details.requestHeaders });
      } else {
        callback({});
      }
    });
  }
}
